from rest_framework.response import Response
from apps.UserControl.models.user import *
from apps.UserControl.serializrs import *
from apps.UserControl.permission import get_permission_list
from utils.response import SuccessResponse
from utils.viewsets import ModelViewSet
from rest_framework.generics import GenericAPIView
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated

from djangoProject import settings
from apps.UserControl.filters.user import UserFilters


class UserModelViewSet(ModelViewSet):
    queryset = User.objects.filter(is_delete=False)
    serializer_class = UserSerializers
    filter_class = UserFilters


    # User.objects.create_user(username='test', password='test')

    # def create(self, request, *args, **kwargs):
    #     res = super().create(request, *args, **kwargs)
    #     return ResponsePackaging(200, res.data, '创建成功！')
        # return Response({
        #     "code": 200,
        #     "data": {"data": res.data},
        #     "message": "OK",
        # })

    # def retrieve(self, request, *args, **kwargs):
    #     res = super().retrieve(request, *args, **kwargs)
    #     return ResponsePackaging(200, res.data, '查询成功！')
        # return Response({
        #     "code": 200,
        #     "data": {"data": res.data},
        #     "message": "OK",
        # })

    # def update(self, request, *args, **kwargs):
    #     res = super().update(request, *args, **kwargs)
    #     return ResponsePackaging(200, res.data, '修改成功！')
        # return Response({
        #     "code": 200,
        #     "data": {"data": res.data},
        #     "message": "OK",
        # })

    @action(methods=['get'], detail=False, url_name='info', permission_classes=[IsAuthenticated])
    def info(self, request, pk=None):
        user = request.user
        perms = get_permission_list(user)
        portrait = None
        try:
            portrait = "http://testering.xyz" + user.portrait.url
        except Exception as e:
            print(e)
        data = {
            'id': user.id,
            'username': user.username,
            'name': user.name,
            # 'roles': user.roles.values_list('name', flat=True),
            'portrait': portrait,
            'perms': perms,
        }
        return Response(data)


class UploadAPIView(GenericAPIView):
    """
    上传头像
    """
    queryset = User.objects.filter(is_delete=False)
    serializer_class = UserSerializers

    def post(self, request, *args, **kwargs):
        if request.method == 'POST':
            # user_id = request.data.get('user_id')
            # User.objects.filter(id=user_id).update(request.FILES.get('portrait'))
            img = request.FILES.get('file')
            path = settings.MEDIA_ROOT + r'/imgs/'

            with open(path + f'{img.name}', 'wb+') as f:
                for chunk in img.chunks():
                    f.write(chunk)

            user_id = request.data.get('user_id')
            # if User.objects.filter(id=user_id) not
            User.objects.filter(id=user_id).update(portrait='imgs/' + img.name)
            data = "http://testering.xyz" + settings.MEDIA_URL + r'imgs/' + img.name
        return SuccessResponse(data={'data': data}, msg='上传成功！')
